package com.earthea.scaffold.common.entity;

import cn.hutool.core.util.PageUtil;
import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.earthea.scaffold.common.enums.HttpCodeEnum;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
public class PageResult<T> extends BaseRsp {
    public static final int DEFAULT_PAGE_SIZE = 10;

    private List<T> rows;

    /**
     * 当前页
     */
    private long page;

    /**
     * 每页结果数
     */
    private long size;

    /**
     * 总页数
     */
    private long totalPage;

    /**
     * 总数
     */
    private long total;

    public PageResult() {
        this(0, DEFAULT_PAGE_SIZE);
    }

    public PageResult(long page, long size) {
        this.page = Math.max(page, 0);
        this.size = size <= 0 ? DEFAULT_PAGE_SIZE : size;
        setCode(HttpCodeEnum.SUCCESS.getCode());
        setMsg(HttpCodeEnum.SUCCESS.getMsg());
    }

    /**
     * 构造
     *
     * @param page  页码，0表示第一页
     * @param size  每页结果数
     * @param total 结果总数
     */
    public PageResult(long page, long size, long total, List<T> rows) {
        this(page, size);
        this.total = total;
        this.rows = rows;
        if (size == 0) {
            this.totalPage = 0;
        }
        this.totalPage = Math.toIntExact(total % size == 0 ? (total / size) : (total / size + 1));
    }

    public PageResult(IPage<T> page) {
        this(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }

    /**
     * @return 是否第一页
     */
    public boolean isFirst() {
        return this.page == 0 || this.page == 1;
    }

    /**
     * @return 是否最后一页
     */
    public boolean isLast() {
        return this.page >= (this.totalPage - 1);
    }

    /**
     * @return 是否为空
     */
    public boolean isEmpty() {
        return this.total == 0;
    }
}
